<!-- admin.html -->
{% extends "base.html" %}

{% block content %}
    <div class="container dashboard">
        <div class="dashboard-sidebar">
            <h2 class="dashboard-title"><i class="fas fa-user-shield"></i> 管理员面板</h2>
            <ul class="dashboard-menu">
                <li><a href="#" class="active" onclick="showSection('weather-section')"><i class="fas fa-cloud-sun-rain"></i> 天气信息</a></li>
                <li><a href="#" onclick="showSection('response-section')"><i class="fas fa-bullhorn"></i> 应急响应</a></li>
                <li><a href="#" onclick="showSection('users-section')"><i class="fas fa-users"></i> 用户管理</a></li>
                <li><a href="#" onclick="showSection('rescuers-section')"><i class="fas fa-user-md"></i> 救援人员</a></li>
                <li><a href="#" onclick="showSection('help-section')"><i class="fas fa-hands-helping"></i> 求救信息</a></li>
                <li><a href="#" onclick="showSection('dispatch-section')"><i class="fas fa-tasks"></i> 调度管理</a></li>
            </ul>
        </div>
        
        <div class="dashboard-content">
            <!-- 天气信息部分 -->
            <div id="weather-section" class="dashboard-section">
                <h3 class="section-title"><i class="fas fa-cloud-sun-rain"></i> 天气预警信息</h3>
                <button id="getWeatherBtn" class="btn"><i class="fas fa-sync-alt"></i> 获取天气信息</button>
                
                <div id="weatherInfo" class="info-box weather-card" style="margin-top: 1.5rem;">
                    <div id="weatherStatus"></div>
                    <div id="weatherUpdateTime" class="text-muted small"></div>
                    <ul id="warningsList" class="warning-list mt-3"></ul>
                </div>
            </div>
            
            <!-- 应急响应部分 -->
            <div id="response-section" class="dashboard-section" style="display: none;">
                <h3 class="section-title"><i class="fas fa-bullhorn"></i> 发送应急响应信息</h3>
                <div class="form-group">
                    <textarea id="responseContent" placeholder="输入应急响应信息..." class="form-control"></textarea>
                </div>
                <button id="sendResponseBtn" class="btn"><i class="fas fa-paper-plane"></i> 发送</button>
                <div id="responseStatus" class="mt-3"></div>
            </div>
            
            <!-- 用户管理部分 -->
            <div id="users-section" class="dashboard-section" style="display: none;">
                <h3 class="section-title"><i class="fas fa-users"></i> 用户管理</h3>
                <button id="viewUsersBtn" class="btn"><i class="fas fa-eye"></i> 查看用户</button>
                <div id="usersList" class="info-box mt-3"></div>
            </div>
            
            <!-- 救援人员部分 -->
            <div id="rescuers-section" class="dashboard-section" style="display: none;">
                <h3 class="section-title"><i class="fas fa-user-md"></i> 救援人员管理</h3>
                <button id="viewRescuersBtn" class="btn"><i class="fas fa-eye"></i> 查看救援人员</button>
                <div id="rescuersList" class="info-box mt-3"></div>
            </div>
            
            <!-- 求救信息部分 -->
            <div id="help-section" class="dashboard-section" style="display: none;">
                <h3 class="section-title"><i class="fas fa-hands-helping"></i> 用户求救信息</h3>
                <button id="viewHelpRequestsBtn" class="btn"><i class="fas fa-eye"></i> 查看求救信息</button>
                <div id="helpRequestsList" class="info-box mt-3"></div>
            </div>
            
            <!-- 调度管理部分 -->
            <div id="dispatch-section" class="dashboard-section" style="display: none;">
                <h3 class="section-title"><i class="fas fa-tasks"></i> 调度救援人员</h3>
                <div class="form-group">
                    <label for="rescuerSelect">选择救援人员</label>
                    <select id="rescuerSelect" class="form-control"></select>
                </div>
                <div class="form-group">
                    <label for="rescuerMessage">消息内容</label>
                    <textarea id="rescuerMessage" class="form-control" placeholder="输入消息..."></textarea>
                </div>
                <button id="sendToRescuerBtn" class="btn"><i class="fas fa-paper-plane"></i> 发送</button>
                <div id="rescuerMessageStatus" class="mt-3"></div>
                
                <h4 class="mt-4"><i class="fas fa-reply"></i> 救援人员回复</h4>
                <button id="viewRescuerRepliesBtn" class="btn"><i class="fas fa-eye"></i> 查看回复</button>
                <div id="rescuerReplies" class="info-box mt-3"></div>
            </div>
        </div>
    </div>
    
    <script>
        // 显示/隐藏不同部分
        function showSection(sectionId, event) {
            // 隐藏所有部分
            document.querySelectorAll('.dashboard-section').forEach(section => {
                section.style.display = 'none';
            });
            
            // 显示目标部分
            document.getElementById(sectionId).style.display = 'block';
            
            // 更新菜单活动状态
            document.querySelectorAll('.dashboard-menu a').forEach(link => {
                link.classList.remove('active');
            });
            
            // 确保event存在且有currentTarget
            if (event && event.currentTarget) {
                event.currentTarget.classList.add('active');
            }
        }
        
        // 获取天气信息并更新UI的函数
        function fetchWeatherData() {
            fetch('{{ url_for("admin_get_weather") }}')
                .then(response => response.json())
                .then(data => {
                    const weatherStatus = document.getElementById('weatherStatus');
                    const updateTime = document.getElementById('weatherUpdateTime');
                    const warningsList = document.getElementById('warningsList');
                    
                    warningsList.innerHTML = '';
                    
                    if (data.status === 'success') {
                        weatherStatus.innerHTML = `<p class="status-success"><i class="fas fa-check-circle"></i> 最新天气预警 (状态码: ${data.code})</p>`;
                        updateTime.innerHTML = `<i class="fas fa-clock"></i> 更新时间: ${data.updateTime}`;
                        
                        if (data.data && data.data.length > 0) {
                            data.data.forEach(warning => {
                                const li = document.createElement('li');
                                li.className = warning.severity === 'Severe' ? 
                                    'warning-item warning-severe' : 'warning-item';
                                
                                li.innerHTML = `
                                    <h5><i class="fas fa-exclamation-triangle"></i> ${warning.typeName || '天气预警'}</h5>
                                    <p><strong><i class="fas fa-building"></i> 发布单位:</strong> ${warning.sender}</p>
                                    <p><strong><i class="fas fa-shield-alt"></i> 预警等级:</strong> ${warning.severity || '未知'}</p>
                                    <p><strong><i class="fas fa-calendar-alt"></i> 发布时间:</strong> ${warning.pubTime}</p>
                                    <p><strong><i class="fas fa-clock"></i> 影响时间:</strong> ${warning.startTime} 至 ${warning.endTime}</p>
                                    <p>${warning.text}</p>
                                `;
                                warningsList.appendChild(li);
                            });
                        } else {
                            warningsList.innerHTML = '<li class="text-muted"><i class="fas fa-info-circle"></i> 当前没有天气预警信息</li>';
                        }
                    } else {
                        weatherStatus.innerHTML = `<p class="status-error"><i class="fas fa-times-circle"></i> 获取失败: ${data.message || '未知错误'}</p>`;
                    }
                });
        }

        // 加载救援人员列表的函数
        function loadRescuers() {
            fetch('{{ url_for("admin_get_rescuers") }}')
                .then(response => response.json())
                .then(data => {
                    const rescuerSelect = document.getElementById('rescuerSelect');
                    
                    if (data.length > 0) {
                        // 更新救援人员选择下拉框
                        rescuerSelect.innerHTML = '';
                        data.forEach(rescuer => {
                            const option = document.createElement('option');
                            option.value = rescuer.id;
                            option.textContent = rescuer.username;
                            rescuerSelect.appendChild(option);
                        });
                    } else {
                        rescuerSelect.innerHTML = '<option value="">没有救援人员</option>';
                    }
                });
        }

        // 默认显示第一个部分
        document.addEventListener('DOMContentLoaded', function() {
            showSection('weather-section');
            
            // 页面加载时自动获取天气信息
            fetchWeatherData();
            
            // 设置每10分钟自动刷新天气信息
            setInterval(fetchWeatherData, 10 * 60 * 1000);
            
            // 保留手动获取按钮功能
            document.getElementById('getWeatherBtn').addEventListener('click', fetchWeatherData);
            
            // 页面加载时自动加载救援人员列表
            loadRescuers();
            
            // 发送应急响应信息
            document.getElementById('sendResponseBtn').addEventListener('click', function() {
                const content = document.getElementById('responseContent').value;
                if (!content) {
                    alert('请输入应急响应信息');
                    return;
                }
                
                fetch('{{ url_for("admin_send_response") }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `content=${encodeURIComponent(content)}`
                })
                .then(response => response.json())
                .then(data => {
                    const statusDiv = document.getElementById('responseStatus');
                    if (data.status === 'success') {
                        statusDiv.innerHTML = '<p class="status-success"><i class="fas fa-check-circle"></i> 应急响应信息发送成功</p>';
                        document.getElementById('responseContent').value = '';
                    } else {
                        statusDiv.innerHTML = `<p class="status-error"><i class="fas fa-times-circle"></i> ${data.message}</p>`;
                    }
                });
            });
            
            // 查看用户
            document.getElementById('viewUsersBtn').addEventListener('click', function() {
                fetch('{{ url_for("admin_get_users") }}')
                    .then(response => response.json())
                    .then(data => {
                        const usersList = document.getElementById('usersList');
                        if (data.length > 0) {
                            let html = '<h4><i class="fas fa-users"></i> 用户列表</h4><ul class="list-group">';
                            data.forEach(user => {
                                html += `<li class="list-group-item">
                                    <i class="fas fa-user"></i> ${user.username} 
                                    <span class="text-muted">(注册时间: ${user.created_at})</span>
                                </li>`;
                            });
                            html += '</ul>';
                            usersList.innerHTML = html;
                        } else {
                            usersList.innerHTML = '<p class="text-muted"><i class="fas fa-info-circle"></i> 没有用户</p>';
                        }
                    });
            });
            
            // 查看救援人员
            document.getElementById('viewRescuersBtn').addEventListener('click', function() {
                fetch('{{ url_for("admin_get_rescuers") }}')
                    .then(response => response.json())
                    .then(data => {
                        const rescuersList = document.getElementById('rescuersList');
                        
                        if (data.length > 0) {
                            // 更新救援人员列表显示
                            let html = '<h4><i class="fas fa-user-md"></i> 救援人员列表</h4><ul class="list-group">';
                            data.forEach(rescuer => {
                                html += `<li class="list-group-item">
                                    <i class="fas fa-user-md"></i> ${rescuer.username} 
                                    <span class="text-muted">(注册时间: ${rescuer.created_at})</span>
                                </li>`;
                            });
                            html += '</ul>';
                            rescuersList.innerHTML = html;
                        } else {
                            rescuersList.innerHTML = '<p class="text-muted"><i class="fas fa-info-circle"></i> 没有救援人员</p>';
                        }
                    });
            });
            
            // 查看求救信息
            document.getElementById('viewHelpRequestsBtn').addEventListener('click', function() {
                fetch('{{ url_for("admin_get_help_requests") }}')
                    .then(response => response.json())
                    .then(data => {
                        const helpRequestsList = document.getElementById('helpRequestsList');
                        if (data.length > 0) {
                            let html = '<h4><i class="fas fa-hands-helping"></i> 求救信息</h4><div class="list-group">';
                            data.forEach(request => {
                                html += `<div class="list-group-item">
                                    <h5><i class="fas fa-user"></i> ${request.user_name}</h5>
                                    <p>${request.content}</p>
                                    <div class="d-flex justify-content-between">
                                        <span class="badge ${request.status === '待处理' ? 'bg-warning' : 'bg-success'}">${request.status}</span>
                                        <small class="text-muted"><i class="fas fa-clock"></i> ${request.timestamp}</small>
                                    </div>
                                </div>`;
                            });
                            html += '</div>';
                            helpRequestsList.innerHTML = html;
                        } else {
                            helpRequestsList.innerHTML = '<p class="text-muted"><i class="fas fa-info-circle"></i> 没有求救信息</p>';
                        }
                    });
            });
            
            // 发送消息给救援人员
            document.getElementById('sendToRescuerBtn').addEventListener('click', function() {
                const rescuerId = document.getElementById('rescuerSelect').value;
                const message = document.getElementById('rescuerMessage').value;
                
                if (!rescuerId || !message) {
                    alert('请选择救援人员并输入消息');
                    return;
                }
                
                fetch('{{ url_for("admin_send_to_rescuer") }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `rescuer_id=${rescuerId}&content=${encodeURIComponent(message)}`
                })
                .then(response => response.json())
                .then(data => {
                    const statusDiv = document.getElementById('rescuerMessageStatus');
                    if (data.status === 'success') {
                        statusDiv.innerHTML = '<p class="status-success"><i class="fas fa-check-circle"></i> 消息发送成功</p>';
                        document.getElementById('rescuerMessage').value = '';
                    } else {
                        statusDiv.innerHTML = `<p class="status-error"><i class="fas fa-times-circle"></i> ${data.message}</p>`;
                    }
                });
            });
            
            // 查看救援人员回复
            document.getElementById('viewRescuerRepliesBtn').addEventListener('click', function() {
                fetch('{{ url_for("admin_get_rescuer_replies") }}')
                    .then(response => response.json())
                    .then(data => {
                        const rescuerReplies = document.getElementById('rescuerReplies');
                        if (data.length > 0) {
                            let html = '<h4><i class="fas fa-reply"></i> 救援人员回复</h4><div class="list-group">';
                            data.forEach(reply => {
                                html += `<div class="list-group-item">
                                    <h5><i class="fas fa-user-md"></i> ${reply.sender_name}</h5>
                                    <p>${reply.content}</p>
                                    <small class="text-muted"><i class="fas fa-clock"></i> ${reply.timestamp}</small>
                                </div>`;
                            });
                            html += '</div>';
                            rescuerReplies.innerHTML = html;
                        } else {
                            rescuerReplies.innerHTML = '<p class="text-muted"><i class="fas fa-info-circle"></i> 没有回复</p>';
                        }
                    });
            });
        });
    </script>
{% endblock %}